//
//  AppDelegate.m
//  shijianpinggu
//
//  Created by apple on 2016/12/15.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "AppDelegate.h"
#import "YTabBarController.h"
#import "YLoginViewController.h"
#import <MeiQiaSDK/MeiQiaSDK.h>
#import <MQToast.h>
#import "MQServiceToViewInterface.h"

/// 个推开发者网站中申请App时，注册的AppId、AppKey、AppSecret
#define kGtAppId           @"JHVPs1qADM8rLsoo6HScP8"
#define kGtAppKey          @"l8R4qHK4Vl95jYOFybHxf4"
#define kGtAppSecret       @"CEgpYRqQmj6VgUIiXVL6z8"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //改变状态栏为白色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    
    
    
    
    //1.创建窗口
    self.window = [[UIWindow alloc] init];
    self.window.frame = [UIScreen mainScreen].bounds;
    self.window.backgroundColor = [UIColor whiteColor];
    //2.显示窗口（成为主窗口）
    [self.window makeKeyAndVisible];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"]){
        
        
        NSLog(@"第一次启动");
    }else {
        
        NSLog(@"已经不是第一次启动了");
        
        
    }

    if (!([[NSUserDefaults standardUserDefaults] stringForKey:@"userid"])) {
        YLoginViewController *loginVC = [YLoginViewController new];
        self.window.rootViewController = loginVC;
    }else{
        YTabBarController *tableVC = [[YTabBarController alloc]init];
        //[tableVC showBadgeOnItmIndex:1];
        
        self.window.rootViewController = tableVC;
    }
    
    
    
    
    // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    // 注册 APNs
    [self registerRemoteNotification];
    
    
    //如果需要角标显示需要调用系统方法设置
    [GeTuiSdk resetBadge]; //重置角标计数
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [self loadDataFormUrl];
    
    //[self versionUpdate];
    [self configureMeiqia];
    
    return YES;
}


#pragma mark - 配置meiqia SDK
- (void)configureMeiqia{
    
    //初始化meiqia SDK
    [MQManager initWithAppkey:@"7429cf9bf0d1b1fa8e30d8c84680a0e8" completion:^(NSString *clientId, NSError *error) {
        if (!error) {
            NSLog(@"美洽 SDK：初始化成功");
        } else {
            NSLog(@"error:%@",error);
        }
        
        [MQServiceToViewInterface getUnreadMessagesWithCompletion:^(NSArray *messages, NSError *error) {
            [UIApplication sharedApplication].applicationIconBadgeNumber = messages.count;
        }];

        
    }];
    
    //在聊天界面外，监听是否收到了客服消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNewMQMessages:) name:MQ_RECEIVED_NEW_MESSAGES_NOTIFICATION object:nil];

 
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNewMQMessages:) name:MQ_RECEIVED_NEW_MESSAGES_NOTIFICATION object:nil];
}


//App 进入后台时，关闭美洽服务, 通知美洽服务端发送消息至开发者的服务端,实现消息推送
- (void)applicationDidEnterBackground:(UIApplication *)application {
    [MQManager closeMeiqiaService];
}

//App 进入前台时，开启美洽服务
- (void)applicationWillEnterForeground:(UIApplication *)application {
    [MQManager openMeiqiaService];
}


- (void)didReceiveNewMQMessages:(NSNotification *)notification {
    NSArray *messages = [notification userInfo][@"messages"];
//    [MQServiceToViewInterface getUnreadMessagesWithCompletion:^(NSArray *messages, NSError *error) {
//        [UIApplication sharedApplication].applicationIconBadgeNumber = messages.count;
//    }];
    
    
//    if (self.window) {
//        [MQToast showToast:[NSString stringWithFormat:@"New message from '%@': %@",[MQManager appKeyForMessage:[messages firstObject]],[[messages firstObject] content]] duration:2 window:self.window];
//    }
}


/** 注册 APNs */
- (void)registerRemoteNotification {
    /*
     警告：Xcode8 需要手动开启"TARGETS -> Capabilities -> Push Notifications"
     */
    
    /*
     警告：该方法需要开发者自定义，以下代码根据 APP 支持的 iOS 系统不同，代码可以对应修改。
     以下为演示代码，注意根据实际需要修改，注意测试支持的 iOS 系统都能获取到 DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
}
/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    
    // 向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:token];
    
    //上传设备deviceToken，以便美洽自建推送后，迁移推送
    [MQManager registerDeviceToken:deviceToken];

}


- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    NSLog(@"注册失败--------%@",error);
}


- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result{
    
    
    
}

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    /// Background Fetch 恢复SDK 运行
    [GeTuiSdk resume];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // 将收到的APNs信息传给个推统计
    
    
    [GeTuiSdk handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    //如果需要角标显示需要调用系统方法设置
    [GeTuiSdk resetBadge];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [self loadDataFormUrl];
    
}


#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    NSLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

//  iOS 10: 点击通知进入App时触发，在该方法内统计有效用户点击数
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);
    
    // [ GTSdk ]：将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    
    [GeTuiSdk resetBadge]; //重置角标计数
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    completionHandler();
}

#endif
/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
    
    [[NSUserDefaults standardUserDefaults] setObject:clientId forKey:@"cid"];
}

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    //个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    NSLog(@"\n>>>[GexinSdk error]:%@\n\n", [error localizedDescription]);
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}



//进入前台
- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    [GeTuiSdk resetBadge];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    [self loadDataFormUrl];
    
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
//请求数据（请求服务器角标归零）
-(void)loadDataFormUrl{
    if ([[NSUserDefaults standardUserDefaults] stringForKey:@"cid"]) {
        
    
    NSDictionary *parameter = @{@"contactid":[[NSUserDefaults standardUserDefaults] stringForKey:@"cid"]};
    
    //    NSLog(@"%@",dict);
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:@"http://wangan.ldynet.cn/index.php/IndexAppSet/clear_superscript" parameters:parameter constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"11111111111111%@", dic);
        NSLog(@"11111111111111%@", dic[@"code"]);
        NSLog(@"11111111111111%@", dic[@"message"]);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败
        // [self alertWithString:@"请稍后再试"];
    }];
    }
    
    //[self loginUrl];
}
////版本更新
//-(void)versionUpdate{
//    //获得当前发布的版本
//    //    __weak typeof(self) weakSelf=self;
//    
//    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        
//        //        typeof(self) strongSelf=weakSelf;
//        // 耗时的操作---获取某个应用在AppStore上的信 息，更改id就行
//        NSString *string = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://itunes.apple.com/lookup?id=1215482078"]
//                                                    encoding:NSUTF8StringEncoding error:nil];
//        if (string!=nil)
//        {
//            NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            
//            NSString *version = [[[dic objectForKey:@"results"]firstObject]objectForKey:@"version"];
//            
//            NSString *updateInfo = [[[dic objectForKey:@"results"]firstObject]objectForKey:@"releaseNotes"];
//            
//            //获得当前版本
//            NSString *currentVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"];
//            
//            NSLog(@"version-------%@",version);
//            NSLog(@"currentVersion--------%@",currentVersion);
//
//            
//            
//                // 更新界面
//                
//                if ( version &&![version isEqualToString:currentVersion]) {
//                    //有新版本
////                    NSString *message = [NSString stringWithFormat:@"%@\n",updateInfo];
////                    message=@"部分功能修复或升级，为了更好的体验程序，请前往更新";//使用中此行注释
////                    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"有新版本发布啦!" message:message delegate:self cancelButtonTitle:@"忽略" otherButtonTitles:@"前往更新", nil];
//                    //                [strongSelf willPresentAlertView:alertView];//此方法iOS 7.0之后就不能用
//                    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:UIAlertControllerStyleAlert];
//                    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//                        NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
//                    }];
//                    [alertC addAction:otherAction];
//                    //[[self getCurrentVC] presentViewController:alertC animated:YES completion:nil];
//                    [[self getCurrentVC].navigationController showDetailViewController:alertC sender:nil];
//                }else{
//                    //已是最高版本
//                    //                NSLog(@"已经是最高版本");
//                }
//            
//            
//        }
//    });
//}
//
////获取当前屏幕显示的viewcontroller
//- (UIViewController *)getCurrentVC
//{
//    UIViewController *result = nil;
//    
//    
//    if (self.window.windowLevel != UIWindowLevelNormal)
//    {
//        NSArray *windows = [[UIApplication sharedApplication] windows];
//        for(UIWindow * tmpWin in windows)
//        {
//            if (tmpWin.windowLevel == UIWindowLevelNormal)
//            {
//                self.window = tmpWin;
//                break;
//            }
//        }
//    }
//    
//    UIView *frontView = [[self.window subviews] lastObject];
//    id nextResponder = [frontView nextResponder];
//    
//    if ([nextResponder isKindOfClass:[UIViewController class]]){
//        result = nextResponder;
//    }
//    //    else{
//    //        result = self.window.rootViewController;
//    //    }
//    return result;
//}



@end
